<template>
  <div>
    <!-- 顶部面包屑导航 -->
    <Breadcrumb menu="权限列表" submenu="角色列表" />
    <el-card>
      <!-- 添加角色按钮 -->
      <el-button type="primary" @click="addRoleDialogVisible = true"
        >添加角色</el-button
      >

      <!-- 显示角色列表 -->
      <el-table :data="rolesList" border>
        <!-- 展开项 -->
        <el-table-column type="expand">
          <template v-slot="{ row }">
            <el-row
              v-for="(it1, i1) in row.children"
              :key="it1.id"
              :gutter="10"
              :class="['bdbottom', 'vcenter', i1 == 0 ? 'bdtop' : '']"
            >
              <!-- 一级角色权限 -->
              <el-col :span="5">
                <el-tag closable @close="deleteRightById(row, it1)">{{
                  it1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二,三级角色权限 -->
              <el-col :span="19">
                <el-row
                  :gutter="10"
                  :class="['vcenter', 'bdleft', i2 == 0 ? '' : 'bdtop']"
                  v-for="(it2, i2) in it1.children"
                  :key="it2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="deleteRightById(row, it2)"
                      type="success"
                      >{{ it2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18" class="bdleft">
                    <el-tag
                      type="warning"
                      closable
                      @close="deleteRightById(row, it3)"
                      v-for="it3 in it2.children"
                      :key="it3.id"
                      >{{ it3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="id"></el-table-column>
        <el-table-column label="角色名称">
          <template v-slot="{ row }">
            <el-input v-if="row._edit" v-model="row._roleName"> </el-input>
            <span v-else>{{ row.roleName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色描述">
          <template v-slot="{ row }">
            <el-input
              type="textarea"
              :rows="2"
              v-if="row._edit"
              v-model="row._roleDesc"
            >
            </el-input>
            <span v-else>{{ row.roleDesc }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320px">
          <template v-slot="{ row }">
            <EditButton
            style="margin-right:10px"
              v-if="row._edit"
              @cancel="cancelEditRoleInfo(row)"
              @complete="saveEditRoleInfo(row)"
            />
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              round
              v-else
              @click="row._edit = true"
            >
              编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              @click="deleteRoleById(row)"
              icon="el-icon-delete"
              size="mini"
              round
              >删除</el-button
            >
            <!-- 分配权限按钮 -->
            <el-button
              @click="showSetRightDialog(row)"
              type="warning"
              icon="el-icon-setting"
              size="mini"
              round
              >修改权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      @close="addRoleDialogClose"
      :visible.sync="addRoleDialogVisible"
      width="30%"
    >
      <el-form
        ref="addRoleFormRef"
        :model="addRoleForm"
        :rules="addRoleFormRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model.trim="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input
            type="textarea"
            :rows="3"
            v-model.trim="addRoleForm.roleDesc"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      @close="curRoleId = -1"
      :visible.sync="setRightDialogVisible"
      width="30%"
    >
      <el-tree
        ref="treeRef"
        default-expand-all
        node-key="id"
        show-checkbox
        :data="rightsList"
        :props="defaultProps"
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      //角色列表数据
      rolesList: [],
      //控制添加角色对话框显示和隐藏
      addRoleDialogVisible: false,
      //控制分配权限对话框显示和隐藏
      setRightDialogVisible: false,
      //添加角色表单数据
      addRoleForm: {
        roleName: "",
        roleDesc: "",
      },
      //添加角色表单验证对象
      addRoleFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      //权限列表
      rightsList: [],
      defaultProps: {
        children: "children",
        label: "authName",
      },
      //默认选中的节点
      defKeys: [],
      //当前分配要分配权限的角色的id
      curRoleId: -1,
    };
  },
  methods: {
    //获取角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      res.data.forEach((el) => {
        el._roleName = el.roleName;
        el._roleDesc = el.roleDesc;
        el._edit = false;
      });
      this.rolesList = res.data;
    },
    //根据id删除角色权限
    deleteRightById(role, right) {
      this.$confirm(
        `此操作将永久删除权限 ${right.authName}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${right.id}`
          );
          role.children = res.data;
          this.$message({
            type: "success",
            message: `删除权限 ${right.authName} 成功!`,
          });
        })
        .catch((error) => error);
    },
    //监听添加角色对话框关闭
    addRoleDialogClose() {
      this.$refs.addRoleFormRef.resetFields();
    },
    //添加角色
    addRole() {
      this.$$refs.addRoleFormRef.validate(async (val) => {
        if (!val) return;
        this.addRoleDialogVisible = false;
        const { data: res } = await this.$http.post("roles", this.addRoleForm);
        this.$message.success(`添加角色 ${this.addRoleForm.roleName} 成功!`);
        this.rolesList.push({
          ...res.data,
          id: res.data.roleId,
          _edit: false,
          _roleName: res.data.roleName,
          _roleDesc: res.data.roleDesc,
        });
      });
    },
    //根据id删除角色
    deleteRoleById(role) {
      this.$confirm(
        `此操作将永久删除角色 ${role.roleName}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${role.id}`);
          this.rolesList.remove(role);
          this.$message({
            type: "success",
            message: `删除角色 ${role.roleName} 成功!`,
          });
        })
        .catch((error) => error);
    },
    //取消编辑角色
    cancelEditRoleInfo(role) {
      role._edit = false;
      role._roleName = role.roleName;
      role._roleDesc = role.roleDesc;
    },
    //编辑用户角色
    async saveEditRoleInfo(role) {
      await this.$http.put(`roles/${role.id}`, {
        roleName: role._roleName,
        roleDesc: role._roleDesc,
      });
      role.roleName = role._roleName;
      role.roleDesc = role._roleDesc;
      this.$message.success("修改角色信息成功！");
      role._edit = false;
    },
    //获取第三级权限的列表数据
    getLeafKeys(node) {
      if (!node.children) {
        this.defKeys.push(node.id);
        return;
      } else {
        node.children.forEach((element) => this.getLeafKeys(element));
      }
    },
    //显示分配权限对话框
    async showSetRightDialog(role) {
      this.curRoleId = role.id;
      if (this.rightsList.length == 0) {
        const { data: res } = await this.$http.get("rights/tree");
        this.rightsList = res.data;
      } else {
        var _temp = this.rightsList;
        this.rightsList = [..._temp];
      }
      this.defKeys = [];
      this.getLeafKeys(role);
      this.setRightDialogVisible = true;
    },
    //设置权限
    async setRoleRights() {
      this.setRightDialogVisible = false;
      var checkedKeys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      var ids = checkedKeys.join(",");
      await this.$http.post(`roles/${this.curRoleId}/rights`, { rids: ids });
      this.$message.success("分配权限成功");
      this.getRolesList();
    },
  },
  created() {
    this.getRolesList();
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 15px;
}
.bdtop {
  border-top: 1px solid #eee;
}

.bdleft {
  border-left: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
